package com.atguigu.tingshu.common.aspect;

import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.login.TsLogin;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.model.user.UserInfo;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Aspect
@Component
@Slf4j
//全局异常处理

public class TsLoginAspect {
    @Autowired
    private RedisTemplate redisTemplate;

    @Around("execution(* com.atguigu.tingshu.*.api.*.*(..)) && @annotation(tsLogin)")
    public Object doBasicProfiling(ProceedingJoinPoint pjp, TsLogin tsLogin){
        log.info("[认证注解切面]前置逻辑...");
        //1 判断是否登录成功
        //1.1 在请求头中获取token
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes servletRequestAttributes =  (ServletRequestAttributes) requestAttributes;
        String token = servletRequestAttributes.getRequest().getHeader("token");
        String LoginAspect = RedisConstant.USER_LOGIN_KEY_PREFIX + token;
        //1.2 redis中查询token是否失效
        UserInfoVo userInfo = (UserInfoVo) redisTemplate.opsForValue().get(LoginAspect);
        if (tsLogin.required()&& userInfo == null){
            throw new GuiguException(ResultCodeEnum.LOGIN_AUTH);
        }
        if (userInfo != null){
            AuthContextHolder.setUserId(userInfo.getId());
        }
        //2 登录成功，则放行
        Object proceed = null;
        try {
            proceed = pjp.proceed();
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }
        //3 释放UserID信息
        log.info("[认证注解切面]后置逻辑...");
        AuthContextHolder.removeUserId();

        return proceed;
    }


}
